package com.isyscore.os.metadata.utils;

import cn.hutool.core.bean.BeanUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public final class DateUtils {
    static String[] parsePatterns = {"yyyy-MM-dd", "yyyy/MM/dd", "yyyyMMdd",
            "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
            "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyyMMdd HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"};

    public static String format(Date date, String format) {
        if (BeanUtil.isEmpty(date)) {
            return null;
        }
        if (BeanUtil.isEmpty(format)) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        return new SimpleDateFormat(format).format(date);
    }

    /**
     * 获取当前时间
     *
     * @return
     */

    public static Date getNow() {
        return Calendar.getInstance().getTime();
    }


    public static boolean isValidFormat(String format, String value) {

        Date date = null;

        try {

            SimpleDateFormat sdf = new SimpleDateFormat(format);

            date = sdf.parse(value);

            if (!value.equals(sdf.format(date))) {

                date = null;

            }

        } catch (ParseException ex) {

            ex.printStackTrace();

        }

        return date != null;

    }

    public static String getDateFormat(String date) {
        for (String parsePattern : parsePatterns) {
            if (isValidFormat(parsePattern, date)) {
                return parsePattern;
            }
        }
        return null;
    }
}
